﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;

#if UNITY_EDITOR
using UnityEditor;
#endif

[AddComponentMenu("PUEX/Emitter/PointEmitter")]
public class PUEXPointEmitter : PUEXEmitter {

	#region - Editable property
	[Header("PointEmitter:")]
	public bool alignDirection;
	public float randomDeviant;
	#endregion
	
	#region - Lifecycle
	public PUEXPointEmitter ()
	{
		alignDirection = true;
		randomDeviant = 0f;
	}
	#endregion
	
	#region - Emit
	protected override void initParticleVelocity (PUEXParticle particle, int index, int requested)
	{
		if (alignDirection) {
			Vector3 dir = Vector3.forward;

			if (randomDeviant > 0f) {
				dir = PUEXUtils.randomDeviant(dir, randomDeviant);
			}

			particle.direction = particle.originalDirection = emitterToSimulationTransform.MultiplyVector (dir).normalized;
		} else {
			particle.direction = particle.originalDirection = emitterToSimulationTransform.MultiplyVector (Random.insideUnitSphere).normalized;
		}
		
		particle.speed = particle.originalSpeed = startSpeed.getValue (timeFraction);
	}
	#endregion

	#region - Draw
	public void OnDrawGizmos()
	{
		if (!enabled)
			return;
		
		#if UNITY_EDITOR
		Matrix4x4 defaultMatrix = Handles.matrix;
		Handles.matrix = transform.localToWorldMatrix;
		
		Color defaultColor = Handles.color;
		Handles.color = Color.blue;

		Vector3 dir = Vector3.forward * HandleUtility.GetHandleSize (Vector3.zero);
		Handles.DrawLine (Vector3.zero, Vector3.zero + dir * 2f);
		Handles.ConeCap(0, Vector3.zero + dir * 2f, Quaternion.identity, HandleUtility.GetHandleSize(Vector3.zero) * 0.2f);
		
		Handles.color = defaultColor;
		Handles.matrix = defaultMatrix;
		#endif
	}
	#endregion

	#region - Serialization
	public override JsonData save (JsonData systemData)
	{
		JsonData ret = base.save (systemData);

		ret ["align_direction"] = alignDirection;
		ret ["random_deviant"] = randomDeviant;

		return ret;
	}
	#endregion

}
